<?php

namespace app\admin\controller\fastflow\bill;
use app\admin\controller\fastflow\bill\Common;
use app\admin\controller\fastflow\flow\CustomMessage;
use fastflow\api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 合作
 *
 * @icon fa fa-circle-o
 */
class Cooperation extends Common
{
    /**
     * Cooperation模型对象
     * @var \app\admin\model\fastflow\bill\Cooperation
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\fastflow\bill\Cooperation;
        $this->departmentList = $this->model->allDepartmentName();
        $this->view->assign("departmentList", $this->departmentList);
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
	    //dump($this->model->getTypeList());
        $this->api = new api(new CustomMessage());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['department'])
                ->where($where)
                ->order($sort, $order)
                ->select();

            $list = $this->itemsFilter($list);
            foreach ($list['items'] as $row) {
                $row->getRelation('department')->visible(['name']);
                if(isset($row->participating_departments) && !empty($row->participating_departments)) {
                    $department_arr = explode(',', $row->participating_departments);
                    $department = '';
                    foreach ($department_arr as $depart) {
                        $departName = Db::name("department")->where('id', $depart)->value('name');
                        if ($department) {
                            $department .= ',' . (isset($departName) ? $departName : '未知');
                        }
                        else {
                            $department = isset($departName) ? $departName : '未知';
                        }
                    }
                    $row->participating_departments = $department;
                }
            }
            $result = array("total" => $list['total'], "rows" => $list['items']);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['participating_departments'] = implode(',',$params['participating_departments']);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 考核
     **/
    public function check($id='')
    {
        $ids = input()['ids'];  //id集合
        for($i=0;$i<count($ids);$i++){
            $year = date("Y");
            //查询合作信息
            $info = $this->model->where(['id' => $ids[$i]])->where('status',2)->find();
            //查询节点信息
            $procedureInfo = Db::name('examine')->where(['partner_id' => $info['id']])->where('year',$year)->find();
            //判断合作信息存在，节点信息不存在
            if(isset($info) && !empty($info) && empty($procedureInfo)) {
                //增加节点流程
                $procedure = [
                    'initiator_id'            => $info['initiator_id'],
                    'partner_id'              => $info['id'],
                    'year'                    => $year,
                    'createtime'              => time(),
                    'updatetime'              => time(),
                ];
                $procedureID = Db::name('examine')->insertGetId($procedure);
                //发起节点
                $row = [
                    'bill'             => 'fa_examine',
                    'bill_id'          => $procedureID,
                    'ebill_id'         => '',
                    'flow_id'          => 2,
                    'checkcontent'     => '',
                    'file_name'        => '',
                    'carbon_scope'     => 1,
                    'carbon_receiver'  => '',
                    'carbon_range'     => 1,
                ];
                $res = $this->api->startFlow($row);
                \think\Log::info('----流程处理结果----' . implode(',',$res));
            }
        }
        //  return $this->view->fetch();
        return json(1);
    }
	
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('TypeList', build_select('row[type]', $this->model->getTypeList(), $row['type'], ['class' => 'form-control selectpicker']));
        $this->view->assign('participatingList', build_select('row[participating_departments][]',$this->departmentList, $row['participating_departments'], ['class' => 'form-control selectpicker','multiple'=>'']));
        return parent::edit($ids);
    }
}